package com.md24housecall.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.md24housecall.activity.AddPatientActivity;
import com.md24housecall.activity.IHealthActivity;
import com.md24housecall.activity.R;
import com.md24housecall.adapter.PatientAdapter;
import com.md24housecall.adapter.PatientAdapter.OnDeleteListener;
import com.md24housecall.manager.CacheManager;
import com.md24housecall.manager.DimenManager;
import com.md24housecall.manager.SkypeManager;
import com.md24housecall.model.User;
import com.md24housecall.model.UserAccountIHealth;
import com.md24housecall.net.ParsingUtils;
import com.md24housecall.net.UrlBuilder;
import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyLog;
import com.md24housecall.util.Utils;
import com.md24housecall.view.PagingListView;
import com.md24housecall.view.PagingListView.PagingListViewListener;
import com.md24housecall.view.RatioImageView;

public final class PatientFragment extends HomeFragment implements OnItemClickListener,PagingListViewListener {
	private static final String KEY_TAB_POSITION = "TestFragment:Position";
	private int mTabPosition = 0;
	private GlobalConstant constant=GlobalConstant.getInstance();
//	private boolean isGetData=false;
	private Utils util=Utils.getInstance();
	private AQuery mAQuery;
	private PagingListView lvMultiAccount;
	private Button btnAddAccount;
	private String patientUrl="";
	private PatientAdapter adapter;
	private List<User> listUser=new ArrayList<User>();
	private List<UserAccountIHealth> listUserIHealth=new ArrayList<UserAccountIHealth>();
	
	private List<User> listOriginUser=new ArrayList<User>();
	private List<UserAccountIHealth> listOriginUserIHealth=new ArrayList<UserAccountIHealth>();
	
	private ProgressBar mProgressBar;
	private SkypeManager skype=SkypeManager.getInstance();
	private CacheManager cacheManager;
	private RatioImageView mImgHeader;
	private RelativeLayout relAddAccount;
	private LinearLayout lnearSearch;
	private Button btnSearch,btnCloseSearch;
	private EditText edtKeyWord;
//	private RatioRelativeLayout relBackground;

	public static PatientFragment newInstance(int tabPosition) {
		PatientFragment fragment = new PatientFragment();

		Bundle args = new Bundle();
		args.putInt(KEY_TAB_POSITION, tabPosition);
		fragment.setArguments(args);

		return fragment;
	}


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments() != null) {
			mTabPosition = getArguments().getInt(KEY_TAB_POSITION, 0);
		}
	}

	private void showKeyBoard(){
		InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
			      Context.INPUT_METHOD_SERVICE);
			imm.showSoftInput(edtKeyWord, 0);
	}
	
	private void hideKeyBoard(){
		InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
			      Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(edtKeyWord.getWindowToken(), 0);
	}
	
	private void closeSearchPanel(){
		edtKeyWord.setText("");
		relAddAccount.setVisibility(View.VISIBLE);
		lnearSearch.setVisibility(View.GONE);
		hideKeyBoard();
	}
	
	private void initialize() {
		mAQuery=new AQuery(getActivity());
//		relBackground=(RatioRelativeLayout)mainView.findViewById(R.id.relBackground);
//		relBackground.setRatio(DimenManager.WIDTH_BACKGROUND_PATIENT,
//				DimenManager.HEIGHT_BACKGROUND_PATIENT);
		mImgHeader = (RatioImageView) mainView.findViewById(R.id.imgHeader);
		mImgHeader.setRatio(DimenManager.WIDTH_TAB_HEADER_IMG,
				DimenManager.HEIGHT_TAB_HEADER_IMG);
		mProgressBar=(ProgressBar)mainView.findViewById(R.id.progressBar);
		cacheManager = CacheManager.getInstance(getActivity());
		btnAddAccount=(Button)mainView.findViewById(R.id.btnAddAccount);
		lvMultiAccount=(PagingListView)mainView.findViewById(R.id.lvIhealthAccount);
		lvMultiAccount.setPullLoadEnable(false);
		lvMultiAccount.setPullRefreshEnable(true);
		lvMultiAccount.setOnItemClickListener(this);
		lvMultiAccount.setPagingListViewListener(this);
		
		relAddAccount=(RelativeLayout)mainView.findViewById(R.id.relAddAccount);
		lnearSearch=(LinearLayout)mainView.findViewById(R.id.lnearSearch);
		btnSearch=(Button)mainView.findViewById(R.id.btnSearch);
		btnSearch.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				relAddAccount.setVisibility(View.GONE);
				lnearSearch.setVisibility(View.VISIBLE);
				edtKeyWord.requestFocus();
				showKeyBoard();
			}
		});
		btnCloseSearch=(Button)mainView.findViewById(R.id.btnCloseSearch);
		btnCloseSearch.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				closeSearchPanel();
			}
		});
		
		edtKeyWord=(EditText)mainView.findViewById(R.id.edtKeyWord);
		edtKeyWord.setOnKeyListener(new View.OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if(keyCode==KeyEvent.KEYCODE_BACK){
					MyLog.d(GlobalConstant.TAG, "back key search press");
					if(lnearSearch.getVisibility()==View.VISIBLE){
						closeSearchPanel();
					}
					return true;
				}
				return false;
			}
		});
		edtKeyWord.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				try{
					String charText = edtKeyWord.getText().toString().toLowerCase(Locale.getDefault());
					if(listUser!=null && listUser.size()>0){
						listUser.clear();
					}
					if(listUserIHealth!=null && listUserIHealth.size()>0){
						listUserIHealth.clear();
					}
					if (charText.length() == 0) {
						listUser.addAll(listOriginUser);
						listUserIHealth.addAll(listOriginUserIHealth);
					}else{
						for(int i=0;i<listOriginUser.size();i++)
						{
							User user=listOriginUser.get(i);
							UserAccountIHealth account=listOriginUserIHealth.get(i);
							if (user.getUserName().toLowerCase(Locale.getDefault()).contains(charText) /*|| user.getEmail().toLowerCase(Locale.getDefault()).contains(charText)*/)
							{
								listUser.add(user);
								listUserIHealth.add(account);
							}
						}
					}
		            adapter.notifyDataSetChanged();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
		
		btnAddAccount.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//clear database
				if(skype.getSkypename(getActivity()).equals("")){
					Toast.makeText(getActivity(), getActivity().getString(R.string.msg_skype_account_not_found_when_add), Toast.LENGTH_SHORT).show();
					skype.focusSkype(getActivity());
				}else{
					startActivity(new Intent(getActivity(),AddPatientActivity.class));
				}
			}
		});
	}

	private void confirmDelete(final int position){
	      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
	      alertDialogBuilder.setMessage(R.string.msg_ihealth_delete_confirm);
	      alertDialogBuilder.setPositiveButton(R.string.button_yes, 
	      new DialogInterface.OnClickListener() {
			
	         @Override
	         public void onClick(DialogInterface arg0, int arg1) {
				mAQuery.ajax(String.format(UrlBuilder.URL_DELETE_PATIENT,util.getPreferenceString(constant.KEYUSERID,getActivity(), "") ,listUser.get(position).getId()),String.class,new AjaxCallback<String>(){
					@Override
					public void callback(String url, String object,
							AjaxStatus status) {
						// TODO Auto-generated method stub
						super.callback(url, object, status);
						android.util.Log.d(GlobalConstant.TAG, "result delete patient: "+object);
						if(status.getCode()==200){
							if(mProgressBar.getVisibility()==View.GONE)
								mProgressBar.setVisibility(View.VISIBLE);
							refreshListUser();
						}
					}
				});
	         }
	      });
	      alertDialogBuilder.setNegativeButton(R.string.button_no, 
	      new DialogInterface.OnClickListener() {
				
	         @Override
	         public void onClick(DialogInterface dialog, int which) {
	            
			 }
	      });
		    
	      AlertDialog alertDialog = alertDialogBuilder.create();
	      alertDialog.show();
		    
	   }
	
	private void refreshListUser(){
		mAQuery.ajax(patientUrl, JSONObject.class, new AjaxCallback<JSONObject>(){
			@Override
			public void callback(String url, JSONObject object, AjaxStatus status) {
				if(mProgressBar.getVisibility()==View.VISIBLE)
					mProgressBar.setVisibility(View.GONE);
				lvMultiAccount.stopRefresh();
				MyLog.d(GlobalConstant.TAG,"url patient fragment: "+url);
				if(status.getCode()==200){
					JSONArray jsonArray=null;
					try {
						jsonArray = object.getJSONArray("patients");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					int len=0;
					if(jsonArray!=null)
						len= jsonArray.length();
					MyLog.d(GlobalConstant.TAG,"len patient: "+len);
					if(listUser!=null && listUser.size()>0){
						listUser.clear();
					}
					if(listUserIHealth!=null && listUserIHealth.size()>0){
						listUserIHealth.clear();
					}
					if(listOriginUser!=null && listOriginUser.size()>0){
						listOriginUser.clear();
					}
					if(listOriginUserIHealth!=null && listOriginUserIHealth.size()>0){
						listOriginUserIHealth.clear();
					}
					if(len>0){
						lvMultiAccount.setVisibility(View.VISIBLE);
//						txvNoData.setVisibility(View.GONE);
						for(int i=0;i<len;i++){
							User user;
							try {
								user = ParsingUtils.parseUserManager(jsonArray.getJSONObject(i));
								listUser.add(user);
								listOriginUser.add(user);
								Object obj=jsonArray.getJSONObject(i).get("ihealth_token");
								if(obj instanceof JSONObject){
									JSONObject json_data=jsonArray.getJSONObject(i).getJSONObject("ihealth_token");
									UserAccountIHealth userIHealth=new UserAccountIHealth();
									userIHealth.setId(json_data.getString("id"));
									userIHealth.setToken(json_data.getString("token"));
									userIHealth.setCode(json_data.getString("code"));
									userIHealth.setIhealthId(json_data.getString("ihealth_id"));
									userIHealth.setUserInfo(json_data.getString("user_info"));
									listUserIHealth.add(userIHealth);
									listOriginUserIHealth.add(userIHealth);
								}else{
									MyLog.d(GlobalConstant.TAG, "no data ihealth");
									listUserIHealth.add(null);
									listOriginUserIHealth.add(null);
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
						}
					}else{
						lvMultiAccount.setVisibility(View.VISIBLE);
//						txvNoData.setVisibility(View.VISIBLE);
					}
				}else{
					MyLog.d(GlobalConstant.TAG, "patient: "+status.getCode());
					lvMultiAccount.setVisibility(View.VISIBLE);
					Toast.makeText(getActivity(), status.getMessage(), Toast.LENGTH_LONG).show();
				}
				if(adapter==null){
					adapter=new PatientAdapter(getActivity(), listUser);
					adapter.setOnDeleteListener(new OnDeleteListener() {
						
						@Override
						public void onDeleteComplete(int position) {
							// TODO Auto-generated method stub
							MyLog.d(GlobalConstant.TAG,"position: "+position);
							confirmDelete(position);
						}
					});
					lvMultiAccount.setAdapter(adapter);
				}else{
					adapter.notifyDataSetChanged();
				}
			}
		});
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(constant.isUpdatePatient){
			constant.isUpdatePatient=false;
			if(mProgressBar.getVisibility()==View.GONE)
				mProgressBar.setVisibility(View.VISIBLE);
			refreshListUser();
		}
	}
	@Override
	protected View initView(LayoutInflater inflater,ViewGroup container) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.patient_ihealth, container, false);
	}
	
	@Override
	protected void initLayout() {
		// TODO Auto-generated method stub
		try{
//			getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
			initialize();
			patientUrl=String.format(UrlBuilder.URL_GET_PATIENT, util.getPreferenceString(constant.KEYUSERID, getActivity(), ""));
		}catch (Exception e) {
			// TODO: handle exception
//			e.printStackTrace();
			MyLog.d(GlobalConstant.TAG, "exception onCreateView HelpFragment: "+e.getMessage());
		}
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_TAB_POSITION, mTabPosition);
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
		try {
			Intent intent=new Intent(getActivity(),IHealthActivity.class);
			if (listUserIHealth.get(position - 1) != null) {
				cacheManager.clearActivityReportData();
				cacheManager.clearBloodOxygenData();
				cacheManager.clearBloodPressureData();
				cacheManager.clearGlucoData();
				cacheManager.clearWeightData();
				JSONObject object;
				try {
					object = new JSONObject(listUserIHealth.get(position - 1)
							.getToken());
					util.savePreferenceString(constant.USERID_IHEALTH_KEY,
							getActivity(), object.getString("UserID"));
					util.savePreferenceString(constant.ACCESSTOKEN_IHEALTH_KEY,
							getActivity(), object.getString("AccessToken"));
					util.savePreferenceString(
							constant.REFRESHTOKEN_IHEALTH_KEY, getActivity(),
							object.getString("RefreshToken"));
					intent.putExtra(constant.IHEALTH_NAME_KEY, listUser.get(position-1).getUserName());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Toast.makeText(getActivity(), getString(R.string.msg_ihealth_data_error), Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
				startActivity(intent);
			} else {
				Toast.makeText(getActivity(),
						getActivity().getString(R.string.msg_no_ihealth_data),
						Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			Toast.makeText(getActivity(), getString(R.string.msg_ihealth_data_error), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
	}


	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		refreshListUser();
	}

	
}
